package service

import (
	"log"
	"strconv"
	"testhttp/dao"
	"testhttp/model"
	"time"

	"github.com/kataras/iris/v12"
)

func SearchGoods(params model.HttpParamsGoods) iris.Map {

	var query model.SelectGoods
	query.Where = " is_deleted = ? "
	query.Page = params.Page
	query.Pagesize = params.Pagesize

	if params.Goods != "" {
		query.Where = query.Where + "and goods like '%" + params.Goods + "%'"
		log.Print("Debug queryparam2:", query.Where)
	}
	if params.GoodsSku != "" {
		query.Where = query.Where + "and goods_sku like '%" + params.GoodsSku + "%'"
		log.Print("Debug queryparam3:", query.Where)
	}
	if params.DealerId != "" {
		query.Where = query.Where + "and dealer_id like '%" + params.DealerId + "%'"
		log.Print("Debug queryparam4:", query.Where)
	}

	count := dao.CountGoods(query)
	res, err := dao.SelectGoods(query)
	if err != nil {
		var str = iris.Map{"code": 1, "msg": err}

		return str
	} else {
		var str = iris.Map{"code": 0, "msg": "OK", "count": count, "data": RepRsponse(res)}

		return str
	}

}

func InsertGoods(goods []model.Goods) iris.Map {
	var querydata []model.Goods
	now := time.Now()

	for x := 0; x < len(goods); x++ {
		//验证必填数据
		switch {
		case goods[x].Goods == "":
			log.Print("Error: ", goods[x], " Goods is null!")
		case goods[x].GoodsCode == "":
			log.Print("Error: ", goods[x], " GoodsCode is null!")
		case goods[x].GoodsSku == "default":
			goods[x].GoodsSku = "默认"
		case goods[x].FixedPrice == "":
			log.Print("Error: ", goods[x], " FixedPrice is null!")
		case goods[x].SupplyPrice == "":
			log.Print("Error: ", goods[x], " SupplyPrice is null!")
		default:
			//计算供货折扣c
			a, _ := strconv.ParseFloat(goods[x].SupplyPrice, 64)
			b, _ := strconv.ParseFloat(goods[x].FixedPrice, 64)
			c := a * 100 / b
			goods[x].Discount = strconv.FormatFloat(c, 'f', 3, 64) //float64，f 不做科学计数，保留3为小数

			// 初始化通用字段
			goods[x].CreateTime = now
			goods[x].UpdateTime = now
			goods[x].IsDeleted = 0

			querydata = append(querydata, goods[x])
		}
	}
	success, err := dao.InsertGoods(querydata)
	if err != nil {
		response := iris.Map{
			"Code": 1,   //0 成功，1 失败
			"Msg":  err, //返回异常
		}
		return response
	} else {
		response := iris.Map{
			"code":   0,              //0 成功，1 失败
			"submit": len(goods),     //提交数据条数
			"new":    len(querydata), //新数据条数
			"Insert": success,        //成功插入数据
		}
		return response
	}
}

func UpdateGoods(del int, goods []model.Goods) iris.Map { //del 1代表删除操作，其它代表更新操作
	now := time.Now()
	for x := 0; x < len(goods); x++ {
		goods[x].UpdateTime = now
		if del == 1 {
			goods[x].IsDeleted = 1
		}

		//计算供货折扣c
		a, _ := strconv.ParseFloat(goods[x].SupplyPrice, 64)
		b, _ := strconv.ParseFloat(goods[x].FixedPrice, 64)
		c := a * 100 / b
		goods[x].Discount = strconv.FormatFloat(c, 'f', 3, 64) //float64，f 不做科学计数，保留3为小数

		if goods[x].Remark == "" {
			goods[x].Remark = " "
		}
	}

	response := iris.Map{
		"Code":    0,
		"Success": dao.UpdateGoods(goods),
	}
	return response
}

func GetGoods(id int) []model.Goods {
	res := dao.GetGoods(id)
	return res
}

func RepRsponse(data []model.Goods) []model.HttpResponseGoods { // 封装dealer到前台显示模型中
	res := make([]model.HttpResponseGoods, len(data))

	for y, x := range data {
		res[y].Id = x.Id
		res[y].GoodsId = x.GoodsId
		res[y].Dealer = dao.GetDealer(x.DealerId)
		res[y].Goods = x.Goods
		res[y].GoodsSku = x.GoodsSku
		res[y].GoodsCode = x.GoodsCode
		res[y].WareHouse = x.WareHouse
		res[y].SupplyPrice = x.SupplyPrice
		res[y].FixedPrice = x.FixedPrice
		res[y].Discount = x.Discount
		res[y].Remark = x.Remark
	}
	return res
}

func GetGoodsby(goods, goodsku string) ([]model.Goods, error) {

	var query model.SelectGoods
	query.Where = " is_deleted = ? "
	query.Page = 1
	query.Pagesize = 15
	if goods != "" {
		query.Where = query.Where + "and goods like '%" + goods + "%'"
	}

	if goodsku != "" {
		query.Where = query.Where + "and goods_sku like '%" + goodsku + "%'"
	}

	res, err := dao.SelectGoods(query)

	return res, err

}
